<?php

namespace frontend\extensions;

use yii\base\Behavior;
use yii\web\Controller;
use frontend\extensions\ErrorCode;
use frontend\extensions\ApiHttpException;

/**
 * Desc 验证签名类
 * @author HUI
 */
class HttpSignAuth extends Behavior {

    public $key = 'a3fe3c339a43833d1836c12eda977058';
    public $sign = 'sign';

    /**
     * Desc 绑定事件和处理器，从而扩展类的功能表现
     * * */
    public function events() {
        return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
    }

    public function beforeAction($event) {
        $headers = \Yii::$app->getRequest()->getHeaders();
        if (empty($headers->get('sign')) || empty($this->checkSign($headers->get('sign'), $headers->get('time')))) {
            return (new ApiHttpException())->renderException(new \Exception('非法请求！！！',201));
        }
        return true;
    }

    private function checkSign($sign, $time) {
        //签名20秒内有效
//        if($time+20 < time()){
//            return false;
//        }
        return md5($this->key . $time) === $sign;
    }
    
    

}
